package com.itcc.controller.interceptor;

import com.itcc.controller.fun_handle.HandleBusiness;
import com.itcc.domain.VisitLog;
import com.itcc.service.VisitLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//拦截器配置
@Component
public class ProjectInterceptor implements HandlerInterceptor {

    private String flagUrls;
    String[] targetPrefixes = {
            "/commService/userIp.do",
            "/commService/userAgent.do",
            "/commService/uirViews.do",
            "/commService/cookies.do",
            "/fileService/down.do",
    };

    @Autowired
    private VisitLogService visitLogService;

    @Override   //拦截的原始操作前
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String url = request.getRequestURI();   //获取请求的url
        flagUrls = url; // 记录当前请求的url
        System.out.println("flagUrls:" + flagUrls);
        String[] urls = visitLogService.getAllUrl();    //获取数据库中储存的所有url

        //遍历所有url
        boolean flag = true;
        for (String s : urls){
            if(url.equals(s)){
                flag = false;
                break;
            }
        }
        //如果该url不存在，添加记录
        if((url.startsWith("/commService") || url.startsWith("/fileService"))&& flag){
            visitLogService.insertLog(new VisitLog(url));
        }

        return true;    //继续执行原始Controller操作；返回false 终止原始操作
    }

    @Override   //拦截的原始操作后
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        String url = HandleBusiness.getLocalInetAddress();
        System.out.println("访问的url：" + url);
        // 获取访问的url
        System.out.println("http://localhost:8088" + flagUrls);

    }

    @Override   //拦截的原始操作完成后
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        // 判断是否拦截
        for (String prefix : targetPrefixes) {
            if (flagUrls.startsWith(prefix)) {
                visitLogService.incrementCount(flagUrls);
                break;
            }
        }

    }
}
